/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package translator.storage;

import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import translator.Util;

public class Storage {

    public enum ETranslate {
        EN_CZ_FILE("en_cz_dir.properties"),
        CZ_EN_FILE("cz_en_dir.properties");

        private final String path;
        private ETranslate(String path) {
            this.path = path;
        }
    }

    private static final Logger log = Logger.getLogger(Storage.class);

    private static final String DELIM = ";";

    private final Properties prop;
    private final ETranslate trans;

    public Storage(ETranslate translate) throws IOException {
        prop = new Properties();
        trans = translate;
        load();
    }

    public LinkedHashSet<String> translate(String word) {
        LinkedHashSet<String> result = new LinkedHashSet<String>();
        result.addAll(Arrays.asList(prop.getProperty(word, "").split(DELIM)));
        return result;
    }

    public void add(String word, String... translations) {
        add(word, Arrays.asList(translations));
    }

    public void add(String word, Collection<String> translations) {
        Set<String> meanings = translate(word);
        meanings.addAll(translations);
        String []array = meanings.toArray(new String[0]);
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < array.length; i++) {
            String w = array[i].trim();
            if(w.isEmpty()) {
                continue;
            }
            builder.append(w);
            if(i + 1 != array.length) {
                builder.append(DELIM);
            }
        }
        prop.setProperty(word, builder.toString());
        persist();
    }

    private void load() throws IOException {
        Reader reader = null;
        try {
            reader = new FileReader(getClass().getClassLoader().getResource(trans.path).getFile());
            prop.load(reader);
        } catch(IOException ex) {
            throw ex;
        } finally {
            Util.closeStream(reader);
        }
    }

    private void persist() {
        OutputStream out = null;
        try {
            out = new FileOutputStream(getClass().getClassLoader().getResource(trans.path).getFile());
            prop.store(out, null);
            out.flush();
        } catch (IOException ex) {
            log.error("store to local dictionary failed", ex);
        } finally {
            Util.closeStream(out);
        }
    }




}
